package com.zzzzzz.account.ticket;

import java.util.Date;

import org.springframework.stereotype.Repository;

import com.google.code.morphia.query.Query;
import com.zzzzzz.common.id.UUIDGenerator;
import com.zzzzzz.core.dao.morphia.BaseDao;

@Repository("ticketDao")
public class TicketDaoImpl extends BaseDao implements TicketDao{
	
	public Ticket add(String classPK, String type) {
		Date now = new Date();

		Ticket ticket = new Ticket();
		ticket.setKey(UUIDGenerator.get());
		ticket.setType(type);
		ticket.setClassPK(classPK);
		ticket.setCreateDate(now);
		
		db.save(ticket);
		
		return ticket;
	}

	public String findClassPKByKey(String key, String type) throws NoSuchTicketException, ExpiredTicketException {
		Ticket ticket = findByKeyAndType(key, type);
		return ticket.getClassPK();
	}
	
	private Ticket findByKeyAndType(String key, String type) throws NoSuchTicketException, ExpiredTicketException {
		Query<Ticket> query = db.createQuery(Ticket.class);
		query.field("key").equal(key);
		query.field("type").equal(type);
		Ticket ticket = query.get();
		if(ticket == null){
			throw new NoSuchTicketException(key);
		}else if(isExpired(ticket.getCreateDate(), type)){
			throw new ExpiredTicketException(key);
		}
		return ticket;
	}
	
	private boolean isExpired(Date createDate, String type){
		long time = new Date().getTime()-createDate.getTime();
		if(time > 86400000){
			return true;
		}
		return false;
	}

	public void delByKey(String key) throws NoSuchTicketException {
		try{
			Query<Ticket> query = db.createQuery(Ticket.class);
			query.field("key").equal(key);
			db.delete(query);
		}catch(Exception e){
			throw new NoSuchTicketException(key);
		}
		
	}

}